package com.hngy.educationaladministration.service.serviceImpl;

import com.hngy.educationaladministration.service.WeatherService;
import com.hngy.educationaladministration.utils.DateUtils;
import com.hngy.educationaladministration.utils.RedisUtils;
import com.hngy.educationaladministration.utils.WeatherUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author: 秃头不用洗发水
 * @Date: 2021-06-05
 * @Description:
 */
@Service
public class WeatherServiceImpl implements WeatherService {
    @Autowired
    private RedisUtils redisUtils;

    //key: 127、0、0、1_2021-06-05 value: json
    @Override
    public boolean setWeather(String ip, String weather) {
        String nowDate = DateUtils.getNowDate();
        return redisUtils.setValue(ip + "_" + nowDate, weather);
    }

    //今天时间与 ip地址 相同从redis获取，不同发送请求
    @Override
    public JSONObject getWeather(String ip) {
        String nowDate = DateUtils.getNowDate();
        if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1")) {
            //如果在本地访问就是0:0:0:0:0:0:0:1，是ipv6的表现形式，对应ipv4来说相当于127.0.0.1，也就是本机http://localhost:8088/
            //所以，如果使用http://localhost:8088/默认设置为株洲的一个IP地址，如果部署到线上，就可以正常使用
            //127.0.0.1:8088使用这个就会显示内网ip 不够美观，就没有使用
            ip = "58.45.20.200";
        }
        if (Objects.isNull(redisUtils.getValue(ip + "_" + nowDate))) {
            String city = WeatherUtil.getCityByIp(ip);
            JSONObject weatherReason = WeatherUtil.getWeatherReason(city);
            setWeather(ip, weatherReason.toString());
            return weatherReason;
        } else {
            return JSONObject.fromObject(redisUtils.getValue(ip + "_" + nowDate));
        }
    }
}
